﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PhiStore.Threading;
using System.IO;
using System.Security.Cryptography;

namespace FileSystemAnalysis.Code
{
    class Sha256Worker : Boostable
    {
        SHA256CryptoServiceProvider sha = new SHA256CryptoServiceProvider();
        private Channel<string> inputChannel;
        private Channel<ResultCapsule> outputChannel;
        public Sha256Worker(Channel<string> inputChannel, Channel<ResultCapsule> outputChannel)
        {
            this.inputChannel = inputChannel;
            this.outputChannel = outputChannel;
        }


        private string SHA256(string path)
        {
            FileStream file = new FileStream(path, FileMode.Open);
            byte[] retVal = sha.ComputeHash(file);
            file.Close();

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < retVal.Length; i++)
            {
                sb.Append(retVal[i].ToString("x2"));
            }
            return sb.ToString();
        }

        public void Run()
        {
            try
            {
                while (true)
                {
                    string path = inputChannel.Receive();
                    try
                    {

                        ResultCapsule result = new ResultCapsule();
                        result.path = path;
                        result.sha256 = SHA256(path);

                        outputChannel.Send(result);
                    }
                    catch (IOException)
                    {
                        //ignore
                    }
                    catch (UnauthorizedAccessException)
                    {
                        //ignore file
                    }
                }
            }
            catch (PoisonException)
            {
                outputChannel.Poison();
                //kthxbye
            }
        }
    }
}
